package com.test.config.shiro;

import com.test.entity.Users;
import com.test.service.UserSercice;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserSercice userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        Users users = (Users) getAvailablePrincipal(principals);
        Set<String> roles = new HashSet<>();  //角色
        Set<String> prems = new HashSet<String>(); //权限
        switch (users.getU_Identity()) {
            case "1":
                roles.add("学生");
                break;
            case "2":
                roles.add("老师");
                break;
            case "3":
                roles.add("管理员");
                break;
            case "4":
                roles.add("企业");
                break;
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.addStringPermissions(prems);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        String userName = (String) authcToken.getPrincipal();
        String password = new String((char[]) authcToken.getCredentials());
        Users user = userService.userLogin(userName, password);
        if (null == user) {
            throw new AccountException("用户名或密码错误！");
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户名
                user.getU_password(), //密码
                getName()  //realm name
        );
        return authenticationInfo;
    }
}
